package com.cn.esermis.server;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.cn.esermis.dpld.business.MonitorBusiness;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
 *  消费和存储消息任务
 */
@Log4j2
@Component
public class SendAndStorageProcess{

    @Resource
    private MonitorBusiness business;
    @Resource
    private ThreadPoolTaskExecutor threadTaskExecutor;  //注入线程池

    /**
     * 多线程消费消息
     * @param message
     * @return
     */
    public JSONObject storageMsg(Object message) {

        Future<JSONObject> future = threadTaskExecutor.submit(new Callable<JSONObject>() {  //采用带返回值的方式
            @Override
            public JSONObject call() throws Exception {

                //2.存储消息
                storageMessage(message);

                JSONObject result = new JSONObject();
                result.put("code", "200");
                result.put("msg", "发送消息成功！");
                return result;
            }
        });

        JSONObject jsonResult = new JSONObject();   //返回结果
        try{
            if (future.isDone()){   //线程调度结束时，才获取结果
                jsonResult = future.get();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return jsonResult;      //消息发送与存储结果
    }

    /**
     * 存消息到数据库
     * @param message
     * @return
     */
    private void storageMessage(Object message) {
        try{
            //TODO 这里执行插入消息到数据操作
            JSONObject jsonObject = JSON.parseObject(message.toString());
            business.inboundOperations(jsonObject);
            System.out.println(Thread.currentThread().getName() + "线程插入消息到数据库成功" );
        }catch (Exception e){
            // 存数据异常
            log.error("消息插入数据库异常！数据内容：{}", message);
            e.printStackTrace();
        }
    }
}